package com.shimao.celnet.payment.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shimao.celnet.payment.model.BillForm;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.PPayRefund;
import com.shimao.celnet.payment.model.request.CallIn_outCUPApplicationReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.*;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 * 交易查询接口
 * 外部系统 → 支付系统，数据：交易查询数据
 * Created by Galen on 2018/11/22.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-210外部交易查询<OutPayQueryReqIn> 外部系统 → 支付系统，数据：交易查询数据")
public class CallIn_OutPayQueryReqInController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @Autowired//支付申请
    private PPayService pPayService;

    @Autowired
    private PPayRefundService pPayRefundService;

    @Autowired
    private TLRecordService tlRecordService;

    @RequestMapping(value = "/payQueryReq",method = RequestMethod.POST)
    public String payQueryReqIn(@RequestBody @Valid CallIn_outCUPApplicationReqIn requestJson, BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-210-外部交易查询<OutPayQueryReqIn>请求JSON:" + requestJson.toString());
        PPay pay = pPayService.getByKey(requestJson.getPaymentId());

        if(pay == null){  //校验paymentId
            PPayRefund refund =  pPayRefundService.getByKey(requestJson.getPaymentId());
            if(refund == null ){
                retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "paymentId");
                return retJson.toString();
            }else {
                if(!refund.getTrxid().equals(requestJson.getTrxid())){
                    retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "trxid");
                    return retJson.toString();
                }else {
                    pay = pPayService.getByKey(refund.getPayGuid());
                }
            }
        }else {
            if(!pay.getTrxid().equals(requestJson.getTrxid())){
                retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "trxid");
                return retJson.toString();
            }
        }
        //根据注册信息的商户id获取商户信息
        PPayCust payCust = getTLMessage(pay.getEstateGuid(), pay.getPayType());
        try {
            Map<String, String> map = new TreeMap<String,String>();
            if(FinalUtil.CUP_PAY_TYPE.equals(pay.getPayType())){
                logger.info("========水流号："+pay.getTrxid() +"=========商户号："+payCust.getCustId());
                 map = callOut_tlPublicService.queryCUP(MyDateUtil.NotString(requestJson.getPaymentId()), requestJson.getTrxid(),payCust);
                logger.info("========通联响应参数："+map.toString());
                if("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
                    retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
                    retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
                    retJson.addBody("paymentId",requestJson.getPaymentId());
                    retJson.addBody("trxid",map.get("trxid"));
                    retJson.addBody("chnltrxid",map.get("chnltrxid"));
                    retJson.addBody("trxcode",map.get("trxcode"));
                    retJson.addBody("trxamt",map.get("trxamt"));
                }else {
                    retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
                }
            }else {
                logger.info("========水流号："+pay.getTrxid() +"=========商户号："+payCust.getCustId());
                map = callOut_tlPublicService.query(MyDateUtil.NotString(pay.getGuid()), pay.getTrxid(),payCust);
                logger.info("========通联响应参数："+map.toString());
                if("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
                    retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
                    retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
                    retJson.addBody("paymentId",pay.getGuid());
                    retJson.addBody("trxid",map.get("trxid"));
                    retJson.addBody("chnltrxid",map.get("chnltrxid"));
                    retJson.addBody("trxcode",map.get("trxcode"));
                    retJson.addBody("trxamt",map.get("trxamt"));
                }else {
                    retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
                }
            }
        }catch (Exception e){
            logger.debug("通联异常参数：" + e.getMessage());
            retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
        }finally {
            return retJson.toString();
        }
    }

    /*
     * 功能描述: more+线下通联支付对账接口
     * @Author: Matt
     * @Date: 2019/5/23 11:30
     */
    @RequestMapping(value = "/payQueryBatch",method = RequestMethod.POST)
    public String payQueryBatch(@RequestBody BillForm para){
        JSONObject object = new JSONObject();
        object.put("errcode", "0000");
        object.put("errmsg", "SUCCESS");

        object.put("data", tlRecordService.queryBatch(para));
        return JSON.toJSONString(object);
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }

}
